package org.example.domain.strategy.service.rule.Chain.imp;

import lombok.extern.slf4j.Slf4j;
import org.example.domain.activity.service.IActivityAccountQuota;
import org.example.domain.award.repository.IAwardRepository;
import org.example.domain.award.service.IAwardService;
import org.example.domain.strategy.model.Raffle.StrategyAwardEntity;
import org.example.domain.strategy.model.Raffle.StrategyRuleEntity;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.domain.strategy.service.rule.Chain.AbstractLogicChain;
import org.example.domain.strategy.service.armory.IStrategyDispatch;
import org.example.domain.strategy.service.rule.Chain.factory.DefaultLogicChainFactory;
import org.example.types.common.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain {
    @Autowired
    private IStrategyRepository strategyRepository;

    @Autowired
    private IStrategyDispatch strategyDispatch;

    @Autowired
    private IAwardRepository awardRepository;

    @Autowired
    private IActivityAccountQuota raffleActivityAccountQuota;


    @Override
    public DefaultLogicChainFactory.StrategyAwardVO  logic(Long strategyId, String userId) {

        log.info("进入责任链中的权重逻辑");

        StrategyRuleEntity strategyRuleEntity = strategyRepository.queryStrategyRuleEntityByStrategyIdAndRuleModel(Long.valueOf(strategyId),ruleModel());
        Integer userScore = strategyRepository.queryActivityAccountTotalUseCount(userId,strategyId);
        String ruleValue = strategyRuleEntity.getRuleValue();
        Map<Long , String> ruleWeightMap = getAnalyticalValue(ruleValue);
        Set<Long> keys = ruleWeightMap.keySet();
        List<Long> keysList = new ArrayList<>(keys);
        Collections.sort(keysList ,Collections.reverseOrder());
        Long raffleLevel = keysList.stream()
                .filter(key -> key <= userScore)
                .findFirst()
                .orElse(null);

        if (raffleLevel!=null){
            Integer awardId  = strategyDispatch.getRandomAwardId(Long.valueOf(strategyId), ruleWeightMap.get(raffleLevel));
            //查询相关配置
            String awardConfig = awardRepository.queryAwardConfigByAwardId(awardId);
            return DefaultLogicChainFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .ruleModel(ruleModel())
                    .awardRuleValue(awardConfig)
                    .build();
        }

        return next.logic(strategyId,userId);
    }



    @Override
    public String ruleModel() {
        return DefaultLogicChainFactory.LogicModel.RULE_WEIGHT.getCode();
    }

    private Map<Long, String> getAnalyticalValue(String ruleValue) {
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        Map<Long, String> ruleValueMap = new HashMap<>();
        for (String ruleValueKey : ruleValueGroups) {
            // 检查输入是否为空
            if (ruleValueKey == null || ruleValueKey.isEmpty()) {
                return ruleValueMap;
            }
            // 分割字符串以获取键和值
            String[] parts = ruleValueKey.split(Constants.COLON);
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueKey);
            }
            ruleValueMap.put(Long.parseLong(parts[0]), ruleValueKey);
        }
        return ruleValueMap;
    }
}
